package com.yxw.live_vod_boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.live_vod_boot.dto.collection_video.OnDemandCollectionVideoAddDTO;
import com.yxw.live_vod_boot.dto.collection_video.OnDemandCollectionVideoDeleteDTO;
import com.yxw.live_vod_boot.dto.collection_video.OnDemandCollectionVideoQueryDTO;
import com.yxw.live_vod_boot.dto.collection_video.OnDemandCollectionVideoSingleQueryDTO;
import com.yxw.live_vod_boot.entity.YxOnDemandCollectionVideoEntity;
import com.yxw.live_vod_boot.entity.YxSysUserEntity;
import com.yxw.live_vod_boot.mapper.OnDemandCollectionFolderMapper;
import com.yxw.live_vod_boot.mapper.OnDemandCollectionVideoMapper;
import com.yxw.live_vod_boot.mapper.UserMapper;
import com.yxw.live_vod_boot.service.OnDemandCollectionVideoService;
import com.yxw.live_vod_boot.utils.AssertUtil;
import com.yxw.live_vod_boot.utils.PageUtils;
import com.yxw.live_vod_boot.utils.RedisManager;
import com.yxw.live_vod_boot.vo.CollectionStateVO;
import com.yxw.live_vod_boot.vo.OnDemandCollectionVideoVO;
import com.yxw.yxnet_cd_center.common.constant.RedisIdConstant;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.enums.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author fangmaoxin
 * &#064;date  2023年11月16日
 */
@Slf4j
@Service
public class OnDemandCollectionVideoServiceImpl extends ServiceImpl<OnDemandCollectionVideoMapper, YxOnDemandCollectionVideoEntity> implements OnDemandCollectionVideoService {

    @Autowired
    private OnDemandCollectionFolderMapper folderMapper;

    @Autowired
    private OnDemandCollectionVideoMapper videoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisManager redisManager;

    /**
     * 用户查询自己的收藏视频列表
     */
    @Override
    public PageVO<OnDemandCollectionVideoVO> getCollectionVideoByUserId(Long userId, OnDemandCollectionVideoQueryDTO dto) {
        AssertUtil.isNotNull(userId, ErrorCodeEnum.COLLECTION_USER_ID_ERROR);
        Page<YxOnDemandCollectionVideoEntity> page = new Page<>(dto.getCurrPage(), dto.getPageSize());
        List<OnDemandCollectionVideoVO> list = videoMapper.getCollectionVideoByUserId(page, userId);
        return PageUtils.get(page, list);
    }

    /**
     * 用户新增一个收藏视频
     */
    @Override
    @Transactional
    public int insertCollectionVideoByUserId(Long userId, OnDemandCollectionVideoAddDTO dto) {
        AssertUtil.isNotNull(userId, ErrorCodeEnum.COLLECTION_USER_ID_ERROR);
        LambdaQueryWrapper<YxOnDemandCollectionVideoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YxOnDemandCollectionVideoEntity::getUserId, userId);
        wrapper.eq(YxOnDemandCollectionVideoEntity::getVideoId, dto.getVideoId());
        YxOnDemandCollectionVideoEntity entity = baseMapper.selectOne(wrapper);
        // 判断用户有没有收藏过这个视频
        if (null != entity) { // 不为空则表示收藏了，再点击一次就取消收藏
            OnDemandCollectionVideoDeleteDTO deleteDTO = new OnDemandCollectionVideoDeleteDTO();
            deleteDTO.setVideoId(dto.getVideoId());
            return this.deleteCollectionVideoByUserId(userId, deleteDTO);
        } else { // 为空则表示没有收藏，点击一次新增收藏
            YxOnDemandCollectionVideoEntity collectionVideo = new YxOnDemandCollectionVideoEntity();
            collectionVideo.setUserId(userId);
            collectionVideo.setVideoId(dto.getVideoId());
            collectionVideo.setCollectionTime(new Date());
            LambdaQueryWrapper<YxSysUserEntity> userWrapper = new LambdaQueryWrapper<>();
            userWrapper.eq(YxSysUserEntity::getUserId, userId);
            YxSysUserEntity yxSysUserEntity = userMapper.selectOne(userWrapper);
            if (null != yxSysUserEntity && null != yxSysUserEntity.getUserName()) {
                collectionVideo.setUserName(yxSysUserEntity.getNickName());
            }
            int insert = baseMapper.insert(collectionVideo);
            insertRedisCollectionInfo(userId, dto);
            return insert;
        }
    }

    private void insertRedisCollectionInfo(Long userId, OnDemandCollectionVideoAddDTO dto) {
        //查询总收藏数量
        long cnt = 0L;
        Object obj = redisManager.get(RedisIdConstant.ONDEMAND_VIDEO_COLLECTION_CNT + ":" + dto.getVideoId());
        if (null != obj) {
            cnt = ((Integer) obj).longValue();
        }
        //增加收藏
        redisManager.addBySet(RedisIdConstant.ONDEMAND_VIDEO_COLLECTION + ":" + dto.getVideoId(), userId);
        //收藏数量加1
        redisManager.set(RedisIdConstant.ONDEMAND_VIDEO_COLLECTION_CNT + ":" + dto.getVideoId(), cnt + 1);
    }

    /**
     * 用户删除一个收藏视频
     */
    @Override
    @Transactional
    public int deleteCollectionVideoByUserId(Long userId, OnDemandCollectionVideoDeleteDTO dto) {
        AssertUtil.isNotNull(userId, ErrorCodeEnum.COLLECTION_USER_ID_ERROR);
        LambdaQueryWrapper<YxOnDemandCollectionVideoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YxOnDemandCollectionVideoEntity::getUserId, userId);
        wrapper.eq(YxOnDemandCollectionVideoEntity::getVideoId, dto.getVideoId());
        YxOnDemandCollectionVideoEntity entity = baseMapper.selectOne(wrapper);
        AssertUtil.isNotNull(entity, ErrorCodeEnum.COLLECTION_VIDEO_NO_EXISTS);
        // 查询所有匹配的收藏数据行的ID
        List<Long> videoFolderIds = folderMapper.findCollectionVideoIdsByVideoId(userId, dto.getVideoId());
        // 删除所有匹配的收藏记录
        if (null != videoFolderIds && !videoFolderIds.isEmpty()) {
            folderMapper.deleteCollectionVideosByVideoIds(videoFolderIds);
        }
        int i = baseMapper.deleteById(entity);
        deleteRedisCollectionInfo(dto);
        return i;
    }

    private void deleteRedisCollectionInfo(OnDemandCollectionVideoDeleteDTO dto) {
        // 查询总收藏数量
        long cnt = 0L;
        Object obj = redisManager.get(RedisIdConstant.ONDEMAND_VIDEO_COLLECTION_CNT + ":" + dto.getVideoId());
        if (null != obj) {
            cnt = ((Integer) obj).longValue();
        }
        // 收藏数量-1
        redisManager.set(RedisIdConstant.ONDEMAND_VIDEO_COLLECTION_CNT + ":" + dto.getVideoId(), cnt - 1);
        redisManager.del(RedisIdConstant.ONDEMAND_VIDEO_COLLECTION + ":" + dto.getVideoId());
    }

    /**
     * 用户查询自己有没有收藏某个视频
     */
    @Override
    public CollectionStateVO checkCollectionStateForUser(Long userId, OnDemandCollectionVideoSingleQueryDTO dto) {
        AssertUtil.isNotNull(userId, ErrorCodeEnum.COLLECTION_USER_ID_ERROR);
        LambdaQueryWrapper<YxOnDemandCollectionVideoEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YxOnDemandCollectionVideoEntity::getUserId, userId);
        wrapper.eq(YxOnDemandCollectionVideoEntity::getVideoId, dto.getVideoId());
        YxOnDemandCollectionVideoEntity entity = baseMapper.selectOne(wrapper);
        CollectionStateVO collectionStateVO = new CollectionStateVO();
        collectionStateVO.setCollectionState(null != entity);
        return collectionStateVO;
    }
}